<template>
  <div class="guestbook-wrapper">
    <div class="fullscreen-background" :style="backgroundStyle"></div>
    
    <div class="content-container">
      <div class="input-box">
        <h1 class="title">弹幕留言板</h1>
        <div class="input-group">
          <input
            type="text"
            v-model="content"
            placeholder="说点什么吧..."
            @keyup.enter="handleSubmit"
            class="message-input"
          />
          <button 
            @click="handleSubmit"
            v-show="hasContent"
            class="submit-button"
          >
            发送
          </button>
        </div>
      </div>
    </div>
    
    <div class="danmu-container">
      <vue-danmaku
        ref="danmaku"
        :danmus="displayDanmus"
        useSlot
        :speeds="120"
        :channels="20"
        :randomChannel="true"
        :overlap="false"
        style="height: 100%; width: 100%;"
      >
        <template v-slot:danmu="{ danmu }">
          <span class="danmu-item">
            <img 
              :src="danmu.commentImage || defaultAvatar" 
              class="danmu-avatar" 
              @error="handleImageError" 
            />
            {{ danmu.commentName }}：{{ danmu.content }}
          </span>
        </template>
      </vue-danmaku>
    </div>
  </div>
</template>

<script>
import { ref, computed, onMounted, onUnmounted } from 'vue';
import VueDanmaku from 'vue-danmaku';
import { getGuestbookList, addGuestbook } from '@/api/guestbook';
import defaultAvatar from '@/assets/images/default-avatar.webp';
import bannerBg from '@/assets/images/banner-bg.webp';

export default {
  name: 'GuestBook',
  components: { VueDanmaku },
  setup() {
    const content = ref('');
    const danmaku = ref(null);
    const allDanmus = ref([]);
    const displayDanmus = ref([]);
    let cycleInterval = null;

    const refreshDanmus = () => {
      if (!danmaku.value) return;
      
      danmaku.value.pause();
      danmaku.value.clear();
      
      // 随机选取部分弹幕显示（最多30条）
      const showCount = Math.min(allDanmus.value.length, 30);
      const shuffled = [...allDanmus.value].sort(() => 0.5 - Math.random());
      const showDanmus = shuffled.slice(0, showCount);
      
      showDanmus.forEach(danmu => {
        danmaku.value.addDanmu(danmu);
      });
      
      danmaku.value.play();
    };

    const initDanmus = async () => {
      try {
        const res = await getGuestbookList();
        allDanmus.value = res.data.map(item => ({
          content: item.content,
          commentImage: item.commentImage || defaultAvatar,
          commentName: item.commentName || '游客'
        }));
        refreshDanmus();
      } catch (error) {
        console.error('获取留言失败:', error);
        allDanmus.value = [
          {
            commentImage: defaultAvatar,
            commentName: '系统',
            content: '欢迎来到弹幕留言板'
          }
        ];
        refreshDanmus();
      }
    };

    const startDanmuCycle = () => {
      clearInterval(cycleInterval);
      cycleInterval = setInterval(() => {
        if (allDanmus.value.length > 0) {
          // 每次随机添加3-5条新弹幕
          const randomCount = Math.floor(Math.random() * 3) + 3;
          const shuffled = [...allDanmus.value].sort(() => 0.5 - Math.random());
          shuffled.slice(0, randomCount).forEach(danmu => {
            danmaku.value.addDanmu(danmu);
          });
        }
      }, 15000); // 每15秒添加一次
    };

    const handleSubmit = async () => {
      if (!content.value.trim()) return;
      
      try {
        const guestbookData = {
          content: content.value.trim(),
          commentName: '游客',
          commentImage: defaultAvatar
        };
        
        await addGuestbook(guestbookData);
        await initDanmus();
        content.value = '';
      } catch (error) {
        console.error('提交留言失败:', error);
        alert(`提交失败: ${error.response?.data?.message || error.message}`);
      }
    };

    const handleImageError = (e) => {
      e.target.src = defaultAvatar;
    };

    onMounted(() => {
      initDanmus();
      startDanmuCycle();
    });

    onUnmounted(() => {
      clearInterval(cycleInterval);
    });

    return {
      content,
      danmaku,
      displayDanmus,
      defaultAvatar,
      hasContent: computed(() => content.value.trim().length > 0),
      backgroundStyle: computed(() => ({
        backgroundImage: `url(${bannerBg})`,
        backgroundSize: 'cover',
        backgroundPosition: 'center'
      })),
      handleSubmit,
      handleImageError
    };
  }
};
</script>

<style scoped>
.guestbook-wrapper {
  position: fixed;
  top: 0;
  left: 0;
  width: 100vw;
  height: 100vh;
  overflow: hidden;
}

.fullscreen-background {
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  z-index: -1;
}

.danmu-container {
  position: fixed;
  top: 100px;
  bottom: 10px;
  left: 0;
  width: 100%;
  /* height: 100%; */
  pointer-events: none;
  z-index: 1;
  overflow: hidden;
}

.danmu-item {
  display: inline-flex;
  align-items: center;
  padding: 3px 12px;
  background: rgba(40, 40, 40, 0.7);
  border-radius: 17px;
  font-size: 20px;
  color: white;
  white-space: nowrap;
  margin: 5px 0;
}

.danmu-avatar {
  width: 30px;
  height: 30px;
  border-radius: 50%;
  margin-right: 12px;
  object-fit: cover;
  border: 1px solid rgba(255, 255, 255, 0.3);
}

.content-container {
  position: relative;
  width: 100%;
  max-width: 600px;
  height: 80vh;
  margin: 10vh auto 0;
  display: flex;
  flex-direction: column;
  padding: 20px;
  z-index: 2;
}

.input-box {
  width: 100%;
  padding: 20px;
  border-radius: 10px;
  margin-bottom: 20px;
}

.title {
  color: #ffffff;
  text-align: center;
  margin-bottom: 20px;
  font-size: 24px;
  text-shadow: 0 2px 4px rgba(0, 0, 0, 0.5);
}

.input-group {
  position: relative;
  width: 100%;
  display: flex;
}

.message-input {
  flex: 1;
  padding: 12px 20px;
  padding-right: 80px;
  border: none;
  border-radius: 25px;
  background: rgba(255, 255, 255, 0.3);
  backdrop-filter: blur(5px);
  font-size: 16px;
  color: #ffffff;
  outline: none;
  transition: all 0.3s ease;
  border: 1px solid rgba(255, 255, 255, 0.2);
}

.message-input::placeholder {
  color: rgba(255, 255, 255, 0.7);
}

.message-input:focus {
  background: rgba(255, 255, 255, 0.4);
  box-shadow: 0 0 10px rgba(255, 255, 255, 0.2);
}

.submit-button {
  position: absolute;
  right: 0;
  top: 0;
  height: 100%;
  padding: 0 25px;
  border: none;
  border-radius: 25px;
  background: rgba(64, 158, 255, 0.7);
  color: white;
  font-size: 16px;
  cursor: pointer;
  transition: all 0.3s ease;
  backdrop-filter: blur(5px);
}

.submit-button:hover {
  background: rgba(64, 158, 255, 0.9);
}

@media (max-width: 768px) {
  .content-container {
    height: 95vh;
    padding: 15px;
    max-width: 100%;
  }
  
  .input-box {
    padding: 15px;
  }
  
  .title {
    font-size: 20px;
    margin-bottom: 15px;
  }
  
  .message-input {
    padding: 10px 15px;
    padding-right: 70px;
    font-size: 14px;
  }
  
  .submit-button {
    padding: 0 20px;
    font-size: 14px;
  }
}

@media (max-width: 480px) {
  .content-container {
    padding: 10px;
  }
  
  .input-box {
    padding: 12px;
    margin-bottom: 15px;
  }
}
</style>